package com.example.user.service;


import com.example.user.common.Result;
import com.example.user.mapper.CartMapper;
import com.example.user.response.CartResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class CartService {

    @Autowired
    private CartMapper cartMapper;


    public List<CartResponse> cartSelectPage(Integer userId) {

        List<CartResponse> cartResponseList = cartMapper.cartSelectPage(userId);
        return cartResponseList;
    }

    public Result cancelCart(Integer productId) {
        int count = cartMapper.cancelCart(productId);
        if (count == 0) {
            return Result.error("400", "移除失败!");
        }
        return Result.success("移除成功!");
    }

    public Result calculateTotal(List<Integer> itemIds) {
        BigDecimal totalPrice = BigDecimal.ZERO;
        for (Integer id : itemIds) {
            List<CartResponse> itemList = cartMapper.findById(id);
            if (itemList!= null &&!itemList.isEmpty()) {
                CartResponse item = itemList.get(0);
                BigDecimal price = item.getPrice();
                if (price == null) {
                    // 根据业务需求决定如何处理，这里暂时设置为0
                    price = BigDecimal.ZERO;
                }
                int quantity = item.getQuantity();
                if (quantity < 0) {
                    // 根据业务需求决定如何处理，这里暂时设置为0
                    quantity = 0;
                }
                totalPrice = totalPrice.add(price.multiply(BigDecimal.valueOf(quantity)));
            }
        }
        return Result.success(totalPrice.doubleValue());
    }
}
